/**
 * 用户访问管理
 */
import { Op } from 'sequelize'

class AppVisitorController extends BasicController {

    /**
     * 添加邀请记录
     * @return {[type]} [description]
     */
    async actionInviteCreate() {
        let company = await this.modules('Company').where({ id: $_POST['company_id'] }).first();
        if (!company) {
            throw new Error('公司不存在');
        }
        let check = await this.modules('Visitor.Invite').where({ start_time: $_POST['start_time'], end_time: $_POST['end_time'] }).first();
        if (check) {
            throw new Error('同时段邀请已存在');
        }
        $_POST['UID'] = this.state.user ? this.state.user.id : 1;
        $_POST['building_id'] = company.building_id;
        $_POST['company_id'] = company.id;
        $_POST['status'] = 0;
        $_POST['note'] = '';
        let data = await this.modules('Visitor.Invite').insert($_POST);
        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }

    /**
     * 用户邀请记录
     * @return {[type]} [description]
     */
    async actionInviteIndex() {
        let page = $_POST['page'];
        let number = page && page.number !== undefined ? page.number : 1;
        let size = page && page.size !== undefined ? page.size : 20;
        let UID = this.state.user ? this.state.user.id : 1;
        return await this.modules('Visitor.Invite').where({ UID }).joinWith(['company']).page(number, size).order([
            ['id', 'DESC']
        ]).select();
    }

    /**
     * 用户访问码
     * @return {[type]} [description]
     */
    async actionVisitQrcode() {
        let str = 'https://www.baidu.com?uid=';
        let UID = this.state.user ? this.state.user.id : 1;
        str += UID;
        let setting = await this.getSetting('qrcode_setting');
        let user_qrcode_time = parseInt(setting.user_qrcode_time);
        let time = '';
        if (user_qrcode_time) {
            str += '&time=';
            time = parseInt(Date.now() / 1000) + user_qrcode_time * 60;
            str += time;
        }
        return { content: cipher256(str), time: date('Y-m-d H:i:s', time) };
    }

}

export default AppVisitorController;